﻿using Koala.Framework;
using Koala.Framework.Environment;
using Koala.Framework.Plugins;
using Koala.Framework.Plugins.Descriptors;
using Koala.Framework.Update;
using Koala.JiraTool.PluginManager.Dialogs;
using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace Koala.JiraTool.PluginManager
{
    public partial class MainFormControl : UserControl, IDependency
    {
        #region Field

        private readonly IPluginManager _pluginManager;
        private readonly IPluginFinder _pluginFinder;
        private readonly Lazy<PluginUpdateDialog> _pluginUpdateDialog;
        private readonly IPluginUpdateController _pluginUpdateController;
        private readonly IHost _host;

        #endregion Field

        #region Constructor

        public MainFormControl(IPluginManager pluginManager, IPluginFinder pluginFinder, Lazy<PluginUpdateDialog> pluginUpdateDialog, IPluginUpdateController pluginUpdateController, IHost host)
        {
            _pluginManager = pluginManager;
            _pluginFinder = pluginFinder;
            _pluginUpdateDialog = pluginUpdateDialog;
            _pluginUpdateController = pluginUpdateController;
            _host = host;
            InitializeComponent();
            dgvMain.AutoGenerateColumns = false;
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            DataBind();
        }

        #endregion Constructor

        #region Event

        private void tsbCheckUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                if (!_pluginUpdateController.CheckUpdate())
                {
                    MessageBox.Show("当前插件都是最新的。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                var form = _pluginUpdateDialog.Value;
                form.ShowDialog();
                if (form.DialogResult != DialogResult.OK) return;
                DataBind();
                _host.ReloadPlugins();
            }
            catch
            {
                MessageBox.Show("插件服务器没有打开，请联系开发人员。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tsbInstall_Click(object sender, EventArgs e)
        {
            var result = openFileDialog.ShowDialog();
            if (result != DialogResult.OK)
                return;
            var file = new FileInfo(openFileDialog.FileName);
            if (!file.Exists)
                return;
            try
            {
                _pluginManager.Instanll(new PluginInstanllDescriptor
                {
                    PackagePath = file.FullName
                });
                _host.ReloadPlugins();
                MessageBox.Show("安装成功，Koala Framework Alpha 1版本部分功能可能只有在下次运行程序时生效。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch
            {
                MessageBox.Show(string.Format(@"安装失败，请前往App_Data\Logs\{0}\log.log查看日志文件。", DateTime.Now.ToString("yyyy-MM-dd")), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tsbDel_Click(object sender, EventArgs e)
        {
            var rows = dgvMain.SelectedRows;
            if (rows.Count == 0)
            {
                return;
            }
            var symbolicName = rows[0].Cells["SymbolicName"].Value.ToString();
            var model = _pluginFinder.GetPluginDescriptorBySymbolicName(symbolicName);
            if (string.Equals(model.Group, "Core", StringComparison.OrdinalIgnoreCase))
            {
                MessageBox.Show("不能删除系统核心插件。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (model.Runtime.Assemblies.Any(m => m.IsStrongDependence))
            {
                MessageBox.Show("Koala Framework Alpha 1无法删除存在强依赖程序集的插件。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            try
            {
                _pluginManager.Uninstall(symbolicName);
                _host.ReloadPlugins();
                MessageBox.Show("卸载成功，Koala Framework Alpha 1版本部分功能可能只有在下次运行程序时生效。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception)
            {
                MessageBox.Show(string.Format(@"卸载失败，请前往App_Data\Logs\{0}\log.log查看日志文件。", DateTime.Now.ToString("yyyy-MM-dd")), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion Event

        #region Private Method

        private void DataBind()
        {
            var list = _pluginFinder.GetPluginDescriptors().ToList();
            dgvMain.DataSource = list;
        }

        #endregion Private Method
    }
}